package api;

import jdk.jfr.internal.Utils;
import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author: 成金乘
 * @date: 2023/5/18 16:05
 * @description:
 */
@WebServlet("/blogDelete")
public class BlogDelServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html; charset=utf8");
        //用户是否登录
        HttpSession session = req.getSession(false);
        if (session == null){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户未登录,无法发布博客");
            return;
        }

        User user = (User)session.getAttribute("user");
        if (user == null){
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户未登录,无法发布博客");
            return;
        }

        //获取参数
        String blogId = req.getParameter("blogId");
        if (blogId == null || blogId.equals("")) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("<h3>文章 ID 缺失</h3>");
            return;
        }
        //查询数据库
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectById(Integer.parseInt(blogId));
        if (blog == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("<h3>要删除的文章不存在.</h3>");
            return;
        }
        // 检验是否是本人的文章
        if (user.getUserId() != blog.getUserId()) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("<h3>无权限删除别人的文章.</h3>");
            return;
        }

        blogDao.delete(Integer.parseInt(blogId));
        resp.sendRedirect("blog_list.html");
    }


}
